#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
主窗口UI模块
"""

import sys
import logging
from PyQt6.QtWidgets import (
    QMainWindow, QTabWidget, QVBoxLayout, QHBoxLayout,
    QWidget, QLabel, QPushButton, QStatusBar, QToolBar,
    QMessageBox
)
from PyQt6.QtCore import Qt, QSize
from PyQt6.QtGui import QIcon, QAction

# 导入核心模块
from app.core.database import Database
from app.core.task_scheduler import TaskScheduler

# 导入页面模块
from app.ui.pages.dashboard import DashboardPage
from app.ui.pages.triggers import TriggersPage
from app.ui.pages.scripts import ScriptsPage
from app.ui.pages.tasks import TasksPage
from app.ui.pages.queue import QueuePage
from app.ui.pages.cluster import ClusterPage
from app.ui.pages.settings import SettingsPage


class MainWindow(QMainWindow):
    """主窗口类"""
    
    def __init__(self, config):
        """初始化主窗口
        
        Args:
            config: 应用配置
        """
        super().__init__()
        self.config = config
        self.setWindowTitle("脚本调度UI")
        self.resize(1200, 800)
        
        # 初始化数据库
        self.database = Database(config)
        self.database.create_tables()
        logging.info("数据库已初始化")
        
        # 初始化任务调度器
        self.task_scheduler = TaskScheduler(config, self.database)
        logging.info("任务调度器已初始化")
        
        # 设置中心部件
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        
        # 创建布局
        self.main_layout = QVBoxLayout(self.central_widget)
        self.main_layout.setContentsMargins(0, 0, 0, 0)
        self.main_layout.setSpacing(0)
        
        # 创建工具栏
        self._create_toolbar()
        
        # 创建标签页
        self._create_tabs()
        
        # 创建状态栏
        self._create_statusbar()
        
        logging.info("主窗口已初始化")
    
    def _create_toolbar(self):
        """创建工具栏"""
        self.toolbar = QToolBar("主工具栏")
        self.toolbar.setIconSize(QSize(32, 32))
        self.toolbar.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextUnderIcon)
        self.addToolBar(self.toolbar)
        
        # 仪表盘
        dashboard_action = QAction("仪表盘", self)
        dashboard_action.triggered.connect(lambda: self.tabs.setCurrentIndex(0))
        self.toolbar.addAction(dashboard_action)
        
        # 触发器
        triggers_action = QAction("触发器", self)
        triggers_action.triggered.connect(lambda: self.tabs.setCurrentIndex(1))
        self.toolbar.addAction(triggers_action)
        
        # 脚本
        scripts_action = QAction("脚本管理", self)
        scripts_action.triggered.connect(lambda: self.tabs.setCurrentIndex(2))
        self.toolbar.addAction(scripts_action)
        
        # 任务
        tasks_action = QAction("任务监控", self)
        tasks_action.triggered.connect(lambda: self.tabs.setCurrentIndex(3))
        self.toolbar.addAction(tasks_action)
        
        # 队列
        queue_action = QAction("队列管理", self)
        queue_action.triggered.connect(lambda: self.tabs.setCurrentIndex(4))
        self.toolbar.addAction(queue_action)
        
        # 集群
        cluster_action = QAction("集群管理", self)
        cluster_action.triggered.connect(lambda: self.tabs.setCurrentIndex(5))
        self.toolbar.addAction(cluster_action)
        
        # 设置
        settings_action = QAction("系统设置", self)
        settings_action.triggered.connect(lambda: self.tabs.setCurrentIndex(6))
        self.toolbar.addAction(settings_action)
    
    def _create_tabs(self):
        """创建标签页"""
        self.tabs = QTabWidget()
        self.tabs.setTabPosition(QTabWidget.TabPosition.South)
        self.tabs.setDocumentMode(True)
        self.tabs.setTabsClosable(False)
        self.tabs.setMovable(False)
        self.main_layout.addWidget(self.tabs)
        
        # 添加页面，传递数据库和任务调度器实例
        self.dashboard_page = DashboardPage(self.config, self.database, self.task_scheduler)
        self.tabs.addTab(self.dashboard_page, "仪表盘")
        
        self.triggers_page = TriggersPage(self.config, self.database, self.task_scheduler)
        self.tabs.addTab(self.triggers_page, "触发器")
        
        self.scripts_page = ScriptsPage(self.config, self.database, self.task_scheduler)
        self.tabs.addTab(self.scripts_page, "脚本管理")
        
        self.tasks_page = TasksPage(self.config, self.database, self.task_scheduler)
        self.tabs.addTab(self.tasks_page, "任务监控")
        
        self.queue_page = QueuePage(self.config, self.database, self.task_scheduler)
        self.tabs.addTab(self.queue_page, "队列管理")
        
        self.cluster_page = ClusterPage(self.config, self.database, self.task_scheduler)
        self.tabs.addTab(self.cluster_page, "集群管理")
        
        self.settings_page = SettingsPage(self.config, self.database)
        self.tabs.addTab(self.settings_page, "系统设置")
    
    def _create_statusbar(self):
        """创建状态栏"""
        self.statusbar = QStatusBar()
        self.setStatusBar(self.statusbar)
        
        # 添加状态信息
        self.status_label = QLabel("就绪")
        self.statusbar.addWidget(self.status_label)
        
        # 添加版本信息
        version = self.config.get("app", {}).get("version", "0.1.0")
        version_label = QLabel(f"版本: {version}")
        self.statusbar.addPermanentWidget(version_label)
    
    def closeEvent(self, event):
        """窗口关闭事件"""
        reply = QMessageBox.question(
            self, "确认退出", "确定要退出应用吗？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            # 关闭数据库连接
            if hasattr(self, 'database') and self.database:
                self.database.close()
                logging.info("数据库连接已关闭")
            
            # 停止任务调度器
            if hasattr(self, 'task_scheduler') and self.task_scheduler:
                self.task_scheduler.stop()
                logging.info("任务调度器已停止")
                
            event.accept()
            logging.info("应用程序已关闭")
        else:
            event.ignore()